package com.homedo.microservice.open.service.gateway.zuul.listener;

import com.homedo.common.util.Detect;
import com.homedo.microservice.open.service.gateway.util.ApplicationContextUtil;
import com.homedo.microservice.open.service.gateway.zuul.conf.ZuulCommonConf;
import com.homedo.microservice.open.service.gateway.zuul.poller.ZuulFilterPollerFromDB;
import com.homedo.microservice.open.service.gateway.zuul.processor.LocalFilterProcessor;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.zuul.FilterFileManager;
import com.netflix.zuul.FilterLoader;
import com.netflix.zuul.FilterProcessor;
import com.netflix.zuul.groovy.GroovyCompiler;
import com.netflix.zuul.groovy.GroovyFileFilter;
import com.netflix.zuul.monitoring.MonitoringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class InitializeServletListener implements ServletContextListener {
    private static final Logger _LOGGER = LoggerFactory.getLogger(InitializeServletListener.class);

    public InitializeServletListener() {
        System.setProperty(DynamicPropertyFactory.ENABLE_JMX, "true");
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try {
//            initInfoBoard();
//            initMonitor();
            initZuul();
//            updateInstanceStatusToEureka();
        } catch (Exception e) {
            _LOGGER.error("Error while initializing zuul gateway.", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        FilterFileManager.shutdown();
        ZuulFilterPollerFromDB.stop();
    }

    private void initZuul() throws Exception {
        _LOGGER.info("过滤器管理器即将启动...");

        ZuulCommonConf zuulCommonConf = ApplicationContextUtil.getApplicationContext().getBean(ZuulCommonConf.class);

        final String preFiltersPath = zuulCommonConf.getZuulFilterPrePath();
        final String postFiltersPath = zuulCommonConf.getZuulFilterPostPath();
        final String routeFiltersPath = zuulCommonConf.getZuulFilterRoutePath();
        final String errorFiltersPath = zuulCommonConf.getZuulFilterErrorPath();
        final String customPath = zuulCommonConf.getZuulFilterCustomPath();

        //加载本地过滤器文件
        FilterProcessor.setProcessor(LocalFilterProcessor.getInstance());//设置自定义处理器
        FilterLoader.getInstance().setCompiler(new GroovyCompiler());
        FilterFileManager.setFilenameFilter(new GroovyFileFilter());
        if (!Detect.notEmpty(customPath)) {
            FilterFileManager.init(5, preFiltersPath, postFiltersPath, routeFiltersPath, errorFiltersPath);
        } else {
            FilterFileManager.init(5, preFiltersPath, postFiltersPath, routeFiltersPath, errorFiltersPath, customPath);
        }
        _LOGGER.info("过滤器管理器启动成功!");

        //从数据库加载过滤器
        startZuulFilterPollerFromDB();

        MonitoringHelper.initMocks();//启动监控 TODO CounterFactory 需要优化 https://www.jianshu.com/p/ebc0a2aef439

    }

    private void startZuulFilterPollerFromDB() {
        ZuulFilterPollerFromDB.start();
        _LOGGER.info("从数据库动态加载过滤器启动成功!");
    }

}
